package com.shenghui.word.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.util.Map;
import java.util.Scanner;

/**
 * @Project: word
 * @Package com.shenghui.word.controller
 * @Description: OlnyOffice-Demo
 * @author: 飞翔的荷兰人
 * @date Date : 2020年09月04日 下午 16:33
 */
@RestController
public class WordController {
    /**
     * 保存路径我服务在Linux上所以使用root
     */
    private static final String PATH = "/root/";

    @PostMapping(value = "/docx/save", produces = "application/json;charset=UTF-8")
    public void saveWord(@RequestParam Map<String, String> map, HttpServletRequest request, HttpServletResponse response) {

        PrintWriter writer = null;
        String body = "";
        try {
            writer = response.getWriter();
            Scanner scanner = new Scanner(request.getInputStream());
            scanner.useDelimiter("\\A");
            body = scanner.hasNext() ? scanner.next() : "";
            scanner.close();
        } catch (Exception ex) {
            writer.write("get request.getInputStream error:" + ex.getMessage());
            return;
        }

        if (body.isEmpty()) {
            writer.write("empty request.getInputStream");
            return;
        }
        JSONObject jsonObj = JSON.parseObject(body);
        System.out.println(body);
        int status = (Integer) jsonObj.get("status");
        System.out.println("status=" + status);
        int saved = 0;
        if (status == 2 || status == 3) //MustSave, Corrupted
        {
            String downloadUri = (String) jsonObj.get("url");
            System.out.println("downloadUri=" + downloadUri);

            try {
                URL url = new URL(downloadUri);
                java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
                InputStream stream = connection.getInputStream();

                if (stream == null) {
                    throw new Exception("Stream is null");
                }

                String path = request.getParameter("path");
                String fileName = downloadUri.substring(downloadUri.lastIndexOf("&") + 1).replace("filename=", "");
                System.out.println("path=" + path);
                System.out.println("fileName=" + fileName);
                File savedFile = new File(PATH + fileName);
                try (FileOutputStream out = new FileOutputStream(savedFile)) {
                    int read;
                    final byte[] bytes = new byte[1024];
                    while ((read = stream.read(bytes)) != -1) {
                        out.write(bytes, 0, read);
                    }

                    out.flush();
                }
                connection.disconnect();

            } catch (Exception ex) {
                saved = 1;
                ex.printStackTrace();
            }

        }
        writer.write("{\"error\":" + saved + "}");
    }
}


